package com.csnf.servlet;

import com.csnf.Dao.AuthoreDao;
import com.csnf.entity.UserAuthors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/authorServlet")
public class AuthoreServlet extends HttpServlet{

        AuthoreDao authoreDao = new AuthoreDao();
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String action = req.getParameter("action");
            if(action==null){
                getAll(req, resp);
            }else{
                switch (action){
                    case "detail":
                        detailAuthor(req, resp);
                        break;
                    case "delete":
//                deleteAuthor(req, resp);
                        break;
                    default:
                        getAll(req, resp);
                }
            }

        }

        private void detailAuthor(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String authorId = req.getParameter("authorId");
            try {
                UserAuthors author = authoreDao.getAuthoreById(Integer.parseInt(authorId));
                req.setAttribute("author", author);
            } catch (Exception e) {
                e.printStackTrace();
            }
            req.getRequestDispatcher("authorDetail.jsp").forward(req, resp);
        }

        private void getAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            try {
                List<UserAuthors> authorsList = authoreDao.getAuthore();
                req.setAttribute("authorsList", authorsList);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            req.getRequestDispatcher("authorList.jsp").forward(req, resp);
        }

}
